package com.example.rabbit.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 延迟交换机
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/11 16:19
 * @Version 1.0.0
 * @Description
 **/
//@Configuration
public class DelayedQueueConfig {

    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    /**
     * 得到延迟交换
     * 1. 交换机名称
     * 2.交换机类型  固定字符串
     * 3.是否持久化
     * 4.是否自动删除
     *
     * @return {@link CustomExchange}
     */
    @Bean(DELAYED_EXCHANGE_NAME)
    public CustomExchange getDelayedExchange() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, arguments);
    }

    @Bean
    public Queue getDelayedQueue() {
        return QueueBuilder.durable(DELAYED_QUEUE_NAME).build();
    }
    /**
     * 因为是自定义交换机类型，所以必须执行构建方法 noargs（）
     * <p>
     * bean 未指定 name 时，其方法名就是 bean name
     */
    @Bean
    public Binding doBinding(
            @Qualifier("getDelayedQueue") Queue delayedQueue,
            @Qualifier(DELAYED_EXCHANGE_NAME) CustomExchange delayedExchange
    ) {
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }

}
